﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;

namespace KoSoft
{
	public static class UtilUrl
	{
		public static string GetBaseUrl(Page page)
		{
			return page.Request.Url.AbsolutePath.Split('?').First();
		}

		public static string Append(Page page, string pKey, string pValue)
		{
			string baseUrl = GetBaseUrl(page);
			Dictionary<string, string> dic = new Dictionary<string, string>();
			var keys = page.Request.QueryString.AllKeys;
			foreach (var key in keys)
				dic.Add(key, page.Request.QueryString[key]);
			if (dic.Keys.Contains(pKey))
				dic[pKey] = pValue;
			else
				dic.Add(pKey, pValue);
			return Splice(baseUrl, dic);
		}

		public static string Remove(Page page, string pKey)
		{
			string baseUrl = GetBaseUrl(page);
			Dictionary<string, string> dic = new Dictionary<string, string>();
			var keys = page.Request.QueryString.AllKeys;
			foreach (var key in keys)
				dic.Add(key, page.Request.QueryString[key]);
			if (dic.Keys.Contains(pKey))
				dic.Remove(pKey);
			return Splice(baseUrl, dic);
		}

		private static string Splice(String baseUrl, Dictionary<string, string> dic)
		{
			StringBuilder sb = new StringBuilder();
			foreach (var item in dic)
			{
				string tag = sb.Length > 0 ? "&" : "?";
				sb.Append(tag);
				sb.Append(item.Key + "=" + item.Value);
			}
			return baseUrl + sb.ToString();
		}

		public static string RemoveAll(Page page)
		{
			return GetBaseUrl(page);
		}
	}
}
